//
//  HomeViewController.swift
//  你的AI
//
//  Created by 丸子 on 2024/6/3.
//

import UIKit
import IQKeyboardManagerSwift
class HomeViewController: BaseViewController {
    var viewModel = HomeViewModel()
    var isOpen:Bool = false {
        didSet {
            self.tableView.reloadData()
        }
    }
    let headerView = HomeTipsHeaderView()
    let disposeBag = DisposeBag()
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: HomeDefaultStyleTableViewCell.self)
        tableView.register(cellWithClass: HomeCheckMoreCell.self)
        tableView.register(cellWithClass: HomeMessageCell.self)
        tableView.register(cellWithClass: HomeRemmendCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        return tableView
    }()
    lazy var inputViwe: HomeInputVIew = {
        let view = HomeInputVIew()
        return view
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //        IQKeyboardManager.shared.keyboardDistanceFromTextField = -bottomSafeAreaHeight
        //        IQKeyboardManager.shared.keyboardDistanceFromTextField = -(kMusicBarHeight - 13)
        IQKeyboardManager.shared.enable = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //        viewModel.stopTimer()
        IQKeyboardManager.shared.enable = true
        //        IQKeyboardManager.shared.keyboardDistanceFromTextField = -(kMusicBarHeight - 13)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //        IQKeyboardManager.shared.keyboardDistanceFromTextField = 0
        initUI()
        self.view.addSubview(tableView)
        self.view.addSubview(inputViwe)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(inputViwe.snp.top)
        }
        //        inputViwe.snp.makeConstraints { make in
        //            make.bottom.equalTo(-kMusicBarHeight)
        //            make.leading.trailing.equalToSuperview()
        //            make.height.equalTo(56)
        //        }
        inputViwe.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(56)
        }
        inputViwe.sendBtn.setClosureTouchUpInside_k { [weak self] in
            self?.sendMessage()
        }
        bindEvent()
        viewModel.getPlazaList()
        viewModel.loadData()
        self.tableView.tableHeaderView = self.headerView
        
        self.headerView.setOneTappedWithCallback_k { [weak self] in
            let chatVc = HomeChatViewController()
            self?.navigationController?.pushViewController(chatVc)
        }
        
        let userDefaults = UserDefaults.standard
//                userDefaults.set(false, forKey: firstLaunchChatGuideKey)
        if userDefaults.bool(forKey: firstLaunchChatGuideKey) == false {
            let chatGuideView = HomeChatGuideView()
            let rect = getSectionPosition(section: 0) ?? CGRect.zero
            chatGuideView.initUI(rect: CGRect(x: 8, y: rect.origin.y, width: SCREEN_WIDTH - 16, height: 104))
            Appearance.addViewToWindow(chatGuideView)
            chatGuideView.nextGuideBag = { [weak self] in
                //                self?.videoGuide()
            }
        }
        
        
        // 监听键盘事件
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    @objc func keyboardWillShow(notification: NSNotification) {
        if let userInfo = notification.userInfo {
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
            let keyboardHeight = keyboardFrame.height
            
            inputViwe.snp.remakeConstraints { make in
                make.bottom.equalTo(-keyboardHeight)
                make.leading.trailing.equalToSuperview()
                make.height.equalTo(56)
            }
            
            UIView.animate(withDuration: 0.3) {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    @objc func keyboardWillHide(notification: NSNotification) {
        inputViwe.snp.remakeConstraints { make in
            //              make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-kMusicBarHeight)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(56)
        }
        
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }
    //    func videoGuide(){
    //        let videoGuideView = HomeVideoGuideView()
    //        Appearance.addViewToWindow(videoGuideView)
    //        videoGuideView.nextGuideBag = { [weak self] in
    //            self?.drawGuide()
    //        }
    //    }
    //
    //    func drawGuide(){
    //        scrollToSection1(section: 1)
    //        self.view.layoutIfNeeded()
    //        let rect = getSectionPosition(section: 1) ?? CGRect.zero
    //        let drawGuideView = HomeDrawGuideView()
    //        drawGuideView.initUI(rect: rect)
    //        Appearance.addViewToWindow(drawGuideView)
    //        drawGuideView.nextGuideBag = { [weak self] in
    //            self?.messageGuide()
    //        }
    //    }
    //
    //    func messageGuide(){
    //        scrollToSection1(section: 2)
    //        self.view.layoutIfNeeded()
    //        let rect = getSectionPosition(section: 2) ?? CGRect.zero
    //        let msgGuideView = HomeMsgGuideView()
    //        msgGuideView.initUI(rect: rect)
    //        Appearance.addViewToWindow(msgGuideView)
    //    }
    //
    func getSectionPosition(section:Int) -> CGRect? {
        if tableView.numberOfSections > section {
            let sectionRect = tableView.rectForHeader(inSection: section)
            let convertedRect = tableView.convert(sectionRect, to: tableView.superview)
            return convertedRect
        }
        return nil
    }
    //
    //    func scrollToSection1(section:Int) {
    //        if tableView.numberOfSections > section {
    //            let rowCount = tableView.numberOfRows(inSection: section)
    //            if rowCount > 0 {
    //                let indexPath = IndexPath(row: 0, section: section)
    //                tableView.scrollToRow(at: indexPath, at: .top, animated: false)
    //            }
    //        }
    //    }
    
    func bindEvent(){
        self.viewModel.messageEventSubject.subscribe(onNext: { [weak self] code, msg in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.tableView.reloadData()
                if code == 1 { //滚动到底部
                    self.scrollToBottom()
                }else if code == -1 {//隐藏键盘
                    kHideKeyboard()
                }
                if let msg = msg {
                    NDProgressHUD.show(message: msg)
                }
            }
        }).disposed(by: disposeBag)
        viewModel.messageStateSubject.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.inputViwe.sendBtn.isSelected = self.viewModel.isGenerated
        }).disposed(by: disposeBag)
        
        viewModel.reloadDataSubject.subscribe { _ in
            self.tableView.reloadData()
        }.disposed(by: disposeBag)
        
        
    }
    
    func sendMessage(){
        if let text = inputViwe.inputFiled.text, text.count > 0 {
            self.inputViwe.inputFiled.text = ""
            kHideKeyboard()
            self.viewModel.checkWords(message: text)
        }else {
            NDProgressHUD.showSuccess(title: "", subtitle: "请输入你想问的问题!")
        }
    }
    
    func scrollToBottom() {
        tableView.reloadData()
        let numberOfSections = tableView.numberOfSections
        let numberOfRows = tableView.numberOfRows(inSection: numberOfSections - 1)
        if numberOfRows > 0 {
            let indexPath = IndexPath(row: numberOfRows - 1, section: numberOfSections - 1)
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
    
    func initUI(){
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.navigationItem.title = "聊天"
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "icon_home_left"), for: .normal)
        let leftItem = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = leftItem
        
        let rightBtn = UIButton(type: .custom)
        rightBtn.setImage(UIImage(named: "icon_home_sub"), for: .normal)
        rightBtn.backgroundColor = UIColor(hexString: "#464957")
        rightBtn.setTitle("订阅", for: .normal)
        rightBtn.allRound(12)
        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 15)
        rightBtn.layoutButtonWithEdgeInsetsStyle(.Left, space: 5)
        rightBtn.contentEdgeInsets = UIEdgeInsets(top: 2, left: 12, bottom: 3, right: 12)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            if Appearance.shared.accoutModel != nil {
                let vc = SubscribeViewController()
                self?.navigationController?.pushViewController(vc, animated: true)
            }else {
                GlobalRx.loginSubject.onNext(())
            }
        }
    }
    
    func openMenuWithMessage(model:AIMessage, point:CGPoint, index:Int) {
        let vc = AIMenuViewController()
        vc.position = point
        //        vc.transitioningDelegate = /*customTransitioningDelegate*/
        vc.modalPresentationStyle = .custom
        self.present(vc, animated: false)
        
        vc.chooseType = { [weak self] type in
            self?.processingLongPress(type: type, model: model)
        }
    }
    func processingLongPress(type:Int, model:AIMessage) {
        if type == 1 {
            UIPasteboard.general.string = model.message ?? ""
            NDProgressHUD.show(message: "复制成功")
        }else if type == 2 {
            SqlManager.shared.delete(from: AIMessage.self, where: AIMessage.Properties.sort == model.sort ?? 0)
            NDProgressHUD.show(message: "删除成功")
        }else if type == 3 {
            var model = model
            model.collect = true
            SqlManager.shared.update(on: [AIMessage.Properties.collect], with: model, where: AIMessage.Properties.sort == model.sort ?? 0)
            NDProgressHUD.show(message: "收藏成功")
        }
    }
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            let count = self.viewModel.list.count
            if count > 0 {
                return 1
            }else {
                return 0
            }
            //            let count = self.viewModel.list.count
            //            if self.isOpen {
            //                return count + 1
            //            } else {
            //                return min(count, 3) + (count >= 3 ? 1 : 0)
            //            }
        }
        return self.viewModel.messageList.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withClass: HomeRemmendCell.self)
            cell.setData(models: self.viewModel.list)
            cell.chooseBag = { type in
                let model = self.viewModel.list[type]
//                let vc = PlazaChatController()
//                vc.model = model
//                self.navigationController?.pushViewController(vc)
                self.viewModel.sendDefault(question: model.item?.first?.question ?? "", answer: model.item?.first?.answer ?? "")
            }
            return cell
            //            if !self.isOpen {
            //                if indexPath.row == 3 {
            //                    let cell = tableView.dequeueReusableCell(withClass: HomeCheckMoreCell.self)
            //                    cell.tipsLb.text = "显示更多 ↓"
            //                    return cell
            //                }
            //            } else {
            //                if indexPath.row >= self.viewModel.list.count {
            //                    let cell = tableView.dequeueReusableCell(withClass: HomeCheckMoreCell.self)
            //                    cell.tipsLb.text = "折叠显示 ↑"
            //                    return cell
            //                }
            //            }
            ////            let colors = ["#ffc06c", "#95a7fc", "#87e4c2", "#ff86b8"]
            //            let model = self.viewModel.list[indexPath.row]
            //            let cell = tableView.dequeueReusableCell(withClass: HomeDefaultStyleTableViewCell.self)
            //            cell.setup(model: model)
            //
            ////            cell.tipsLb.backgroundColor = UIColor(hexString: colors[indexPath.item % 4])
            //            return cell
        }else {
            let model = self.viewModel.messageList[indexPath.item]
            let cell = tableView.dequeueReusableCell(withClass: HomeMessageCell.self)
            cell.setup(message: model)
            
            cell.chooseLongPress = { [weak self] in
                guard let self = self else { return }
                kHideKeyboard()
                UIView.animate(withDuration: 0.3, animations: {
                    // 动画部分可以为空
                }) { [weak self, weak cell] finished in
                    guard let self = self, let cell = cell else { return }
                    let rect = self.tableView.convert(cell.frame, to: self.view)
                    let point = CGPoint(x: cell.contentV.x, y: rect.origin.y)
                    self.openMenuWithMessage(model: model, point: point, index: indexPath.item)
                }
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            //            if !self.isOpen {
            //                if indexPath.row == 3 {
            //                    self.isOpen = !self.isOpen
            //                    return
            //                }
            //            } else {
            //                if indexPath.row >= self.viewModel.list.count {
            //                    self.isOpen = !self.isOpen
            //                    return
            //                }
            //            }
            //            let model = self.viewModel.list[indexPath.row]
            ////            let chatVC = HomeChatViewController()
            ////            chatVC.model = model
            ////            self.navigationController?.pushViewController(chatVC)
            //            let vc = PlazaChatController()
            //            vc.model = model
            //            self.navigationController?.pushViewController(vc)
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 144
        }else {
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            let view = HomeMsgHeaderVIew()
            view.moreBtn.setClosureTouchUpInside_k { [weak self] in
                //                self?.tabBarController?.selectedIndex = 2
                let vc = PlazaViewController()
                self?.navigationController?.pushViewController(vc, animated: true)
            }
            view.gotoDarkBtn.setClosureTouchUpInside_k { [weak self] in
                let vc = PaintingPageViewController()
                self?.navigationController?.pushViewController(vc)
            }
            return view
        }else {
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 50 + 90
        } else {
            return 0.01
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    //    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    //        if indexPath.section == 0 {
    //            let radius = 10.0
    //            cell.backgroundColor = UIColor.clear
    //            let normalLayer = createLayer(with: radius, bounds: cell.bounds.insetBy(dx: 14.0, dy:0), tableView: tableView, indexPath: indexPath)
    //            let selectLayer = createLayer(with: radius, bounds: cell.bounds.insetBy(dx: 14.0, dy:0), tableView: tableView, indexPath: indexPath)
    //            cell.backgroundView = createBackgroundView(with: normalLayer, bounds: cell.bounds.insetBy(dx: 14.0, dy:0))
    //            cell.selectedBackgroundView = createBackgroundView(with: selectLayer, bounds: cell.bounds.insetBy(dx: 14.0, dy:0))
    //        }
    //    }
    //
    //    func createLayer(with radius: Double, bounds: CGRect, tableView: UITableView, indexPath: IndexPath) -> CAShapeLayer {
    //        let layer = CAShapeLayer()
    //        layer.path = createBezierPath(with: radius, bounds: bounds, tableView: tableView, indexPath: indexPath).cgPath
    //        layer.fillColor = UIColor(hexString: "#FFFFFF").cgColor
    //        return layer
    //    }
    //
    //    func createBezierPath(with radius: Double, bounds: CGRect, tableView: UITableView, indexPath: IndexPath) -> UIBezierPath {
    //        let rowNum = tableView.numberOfRows(inSection: indexPath.section)
    //        if rowNum == 1 {
    //            return UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii:CGSize(width: radius, height: radius))
    //        } else if indexPath.row == 0 {
    //            return UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.topLeft,UIRectCorner.topRight], cornerRadii:CGSize(width: radius, height: radius))
    //        } else if indexPath.row == rowNum-1 {
    //            return UIBezierPath(roundedRect: bounds, byRoundingCorners: [UIRectCorner.bottomLeft,UIRectCorner.bottomRight], cornerRadii:CGSize(width: radius, height: radius))
    //        } else {
    //            return UIBezierPath(rect: bounds)
    //        }
    //    }
    //
    //    func createBackgroundView(with layer: CAShapeLayer, bounds: CGRect) -> UIView {
    //        let bgView = UIView(frame: bounds)
    //        bgView.layer.insertSublayer(layer, at:0)
    //        bgView.backgroundColor = UIColor.clear
    //        return bgView
    //    }
}

extension HomeViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
    open func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        UIImage(named: "icon_nodata")
    }
    
    open func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let text = "点击刷新"
        let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.pingFangSCRegular(ofSize: 15), .foregroundColor: Theme.color.text_d3]
        return NSAttributedString(string: text, attributes: attributes)
    }
    
    func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) {
        self.viewModel.getPlazaList()
    }
    
        func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
            return -navHig()
        }
}
